package antidestiny.utilib.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import antidestiny.utilib.Aide;

/**
 * Created by Hero on 2016/6/26.
 */
public class ZipUtils {
    /**
     * 在zipFile文件中的entrypath路径下添加toadd文件
     * @param toadd
     * @param entryPath
     * @param zipFile
     * @throws IOException
     */
    public static void addFile(File toadd,String entryPath,File zipFile,ZipOutputStream zom)throws IOException{

        try {

            ZipEntry entry = new ZipEntry(entryPath);
            zom.putNextEntry(entry);
            byte[] bytes = FileUtils.read(toadd);
            if (bytes != null)
            {	Aide.t("byte");
                zom.write(bytes);
                zom.flush();
            }
            else Aide.w("no bytes");
            zom.closeEntry();
        }catch (IOException e){
            if (zom!=null){
                zom.closeEntry();
                zom.close();
            }
            throw  e;
        }
        finally {
        }
    }
    public static void compressDir(File dir,File zipFile,boolean cover)throws IOException{
        if (!zipFile.exists()){
            FileUtils.createFileSafely(zipFile,cover);
        }
        ArrayList<File> filesToAdd=FileUtils.allFiles(dir);
        FileOutputStream fo = new FileOutputStream(zipFile);
        CheckedOutputStream cos=new CheckedOutputStream(fo,new CRC32());
        ZipOutputStream zom=new ZipOutputStream(cos);
        for (File file:filesToAdd){
            String entryPath=FileUtils.getSubPath(file, dir);
            Aide.t("entrypath"+entryPath);
            addFile(file, entryPath, zipFile,zom);
        }
        zom.close();
    }
    public static void decompressZip(ZipFile file, String dir){
        Enumeration entries=file.entries();
        InputStream inputStream=null;
        try {
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory())continue;
                inputStream = file.getInputStream(entry);
                FileUtils.write(inputStream,new File(dir+"/"+entry.getName()));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        finally {
             if (inputStream!=null){
                 try {
                     inputStream.close();
                 }catch (IOException e){
                     e.printStackTrace();
                 }
             }
        }
    }

}
